package com.generalbackend.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @author tim.xie
 * @date 2021/11/26 9:32
 */
@Slf4j
public class HttpClientUtil {

    private static ExecutorService fixedThreadPool = null;

    static {
        //设置2个核心线程数
        fixedThreadPool = Executors.newFixedThreadPool(2);
    }

    /**
     * 微信post发送post请求
     * @param httpUrl url地址
     * @param paramStr  模板消息json字符串
     * @return
     */
    public static String doHttpsPost(String httpUrl, String paramStr){
        String res=null;
        URL url = null;
        HttpsURLConnection conn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            url = new URL(httpUrl);
            conn = (HttpsURLConnection) url.openConnection();
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != paramStr) {
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(paramStr.getBytes("UTF-8"));
                outputStream.close();
            }
            //从输入流读取返回内容
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            res=buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if(bufferedReader != null) {

                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                conn.disconnect();
            }

        }
        return  res;
    }

    /**
     * http的post发送post请求
     * @param httpUrl url地址
     * @param paramStr  模板消息json字符串
     * @return
     */
    public static String doHttpPost(String httpUrl,String paramStr){

        String res=null;
        URL url = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != paramStr) {
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(paramStr.getBytes("UTF-8"));
                outputStream.close();
            }
            //从输入流读取返回内容
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            res=buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if(bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                conn.disconnect();
            }

        }
        return  res;
    }

    public static String doHttpPost(String url, JSONObject param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        HttpURLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置连接超时时间
            conn.setConnectTimeout(3000);
            conn.setRequestProperty("Content-type", "application/json;charset=utf-8");
            conn.setRequestProperty("Charset", "UTF-8");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (ConnectException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        log.info("res=" + result);
        return result;
    }

    /**
     * 微信get发送请求
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl){
        String content = "";
        // 这里发送get请求
        HttpGet httpGet = new HttpGet(httpUrl);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                content = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  content;
    }

    /**
     * 微信get发送请求
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl, Map<String, String> params){
        if(params!=null && params.size()!=0) {
            httpUrl += "?";
            ArrayList<String> list = new ArrayList<>();
            params.forEach((key, value) -> {
                list.add(key + "=" + value);
            });
            httpUrl += list.stream().collect(Collectors.joining("&"));
        }
        String content = "";
        // 这里发送get请求
        HttpGet httpGet = new HttpGet(httpUrl);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                content = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  content;
    }

    /**
     * 发送模板消息的方法
     * @param templateMsgUrl 模板消息请求URL
     * @param paramStr  模板消息json字符串
     * @return
     */
    public static String doTemplateMsgPost(String templateMsgUrl,String paramStr){
        String res=null;
        URL url = null;
        HttpsURLConnection conn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            url = new URL(templateMsgUrl);
            conn = (HttpsURLConnection) url.openConnection();
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != paramStr) {
                OutputStream outputStream = conn.getOutputStream();
                //注意编码格式
                outputStream.write(paramStr.getBytes("UTF-8"));
                outputStream.close();
            }
            //从输入流读取返回内容
            inputStream = conn.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            res=buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if(bufferedReader != null) {

                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    //TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                conn.disconnect();
            }

        }
        return  res;
    }


    public static void main(String[] args) {
//        Map<String,String> treeMap = new TreeMap<>();
//        treeMap.put("agent_id","100008");
//        treeMap.put("tel","18458893464");
//        treeMap.put("room_id","MjUwNDcjQGltYW5tQCMxMjQ4NjQjQGltYW5tQCMxNjExNTc0ODAwI0BpbWFubUAjMyNAaW1hbm1AIzYx");
//        treeMap.put("seat_id","[\"MjUwNDdAX0AxMjQ4NjRAX0AxNjExNTc0ODAwQF9AM0BfQDYxQF9AMDAwMDAwMDI2NzA2LTItNEBfQDYxQF9AMUBfQDLmjpI15bqn\"]");
//        treeMap.put("cinema_id","25047");
//        treeMap.put("film_id","124864");
//        treeMap.put("seat_data","[{\"lovestatus\":2,\"seatNo\":\"2排5座\",\"type\":1,\"ColumnNum\":\"4\",\"RowNum\":\"2\",\"SeatCode\":\"MjUwNDdAX0AxMjQ4NjRAX0AxNjExNTc0ODAwQF9AM0BfQDYxQF9AMDAwMDAwMDI2NzA2LTItNEBfQDYxQF9AMUBfQDLmjpI15bqn\"}]");
//        treeMap.put("attach","10njudy6juo");
//        treeMap.put("signid","52fcabd8c8cea79ada64dbd8b801a773");
//        String resukt = doFormDataPost("https://service-g8f5yslp-1303204763.sh.apigw.tencentcs.com/api/order/third/submit", treeMap);
//        System.out.println(resukt);
//        String post = HttpUtil.post("https://service-g8f5yslp-1303204763.sh.apigw.tencentcs.com/api/order/third/submit", treeMap);
//        System.out.println(post);
//        String result = doGet("http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=en&q=计算");
//        Map<String,String> map = new HashMap<>();
//        map.put("client","gtx");
//        map.put("dt","t");
//        map.put("dj","1");
//        map.put("ie","UTF-8");
//        map.put("sl","auto");
//        map.put("tl","en");
//        map.put("q","计算");
//        String r = doGet("http://translate.google.cn/translate_a/single", map);
//        System.out.println(r);
        String get = doGet("http://10.50.1.68/OUT/202151/lic_AiLPHA_WX_H20210800471-4CF4_152333.dat");
        System.out.println(get);
    }


}
